//
//  MallViewController.swift
//  ZCF
//
//  Created by 赵世杰 on 16/3/15.
//  Copyright © 2016年 zhaoshijie. All rights reserved.
//

import UIKit

class MallViewController: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UITableViewDataSource,UITableViewDelegate {
    
    /// 数据
    
    // 头视图图片
    var headImageUrlString:String!
    // 头视图物品信息
    var itemShowArray:Array<AnyObject>!
    // 页数
    var default_Page:Int!
    // 默认cell的数据
    var defaultArray:Array<AnyObject>!
    
    
    /// 控件
    
    // 头视图的总视图
    var headerView:UIView!
    // 头视图的图片
    var headerImageView:UIImageView!
    // collectionView
    var collectionView:UICollectionView!
    
    
    // 中间的
    
    
    @IBOutlet var overallTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationController?.navigationBar.isHidden = true
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = GrayColorInit
        
        // 初始化数据
        self._initDataList()
        
        // 创建视图
        self._initViews()
        
        // 请求数据
        self._requestDataList()
    }
    
    //MARK: -
    func _initDataList()
    {
        self.itemShowArray = Array()
        self.defaultArray = Array()
        self.default_Page = 1
    }
    
    func _initViews()
    {
        // 创建头视图
        self.createHaederView()
        
        self.overallTableView.delegate = self
        self.overallTableView.dataSource = self
        self.overallTableView.separatorStyle = .none
        // 注册
        self.overallTableView .register(UINib(nibName: "ItemShowTCell", bundle: nil), forCellReuseIdentifier: "Tcell")
        
    }
    
    // 创建头视图
    func createHaederView()
    {
        // 总视图View
        self.headerView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 232*(KScreenWidth/640)+10+80+10+40+2))
        self.headerView.backgroundColor = GrayColorInit
        self.overallTableView.tableHeaderView = self.headerView
        
        // 图片视图创建
        self.headerImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 232*(KScreenWidth/640)))
        self.headerView.addSubview(headerImageView)
        
        // 创建水平滑动的图片视图
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: 180, height: 80)
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.scrollDirection = .horizontal
        
        self.collectionView = UICollectionView(frame: CGRect(x: 0, y: headerImageView.bottom+10, width: KScreenWidth, height: 80), collectionViewLayout: flowLayout)
        self.collectionView.backgroundColor = UIColor.white
        self.collectionView.showsHorizontalScrollIndicator = false
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        self.headerView.addSubview(collectionView)
        // 注册
        self.collectionView .register(UINib(nibName: "ItemsShowCCell", bundle: nil), forCellWithReuseIdentifier: "Ccell")
        
        // 创建选择button和下划线
        let array = ["默认","最新上架","人气"]
        for i in 0  ..< 3 
        {
            let button = UIButton(type: .custom)
            let width = KScreenWidth/3.0
            button.frame = CGRect(x: width*CGFloat(i), y: self.collectionView.bottom+10, width: width, height: 40)
            button.backgroundColor = UIColor.white
            button.setTitle(array[i], for: UIControlState())
            button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
            button.titleLabel?.textAlignment = .center
            button.addTarget(self, action: #selector(MallViewController.buttonAction(_:)), for: .touchUpInside)
            button.tag = 140 + i
            self.headerView.addSubview(button)
            if(i != 0)
            {
                button.setTitleColor(UIColor ( red: 0.4337, green: 0.4337, blue: 0.4337, alpha: 1.0 ), for: UIControlState())
            }
            else
            {
                button.setTitleColor(UIColor.black, for: UIControlState())
                let underlineView = UIView(frame: CGRect(x: 0, y: button.bottom, width: 40, height: 2))
                underlineView.center.x = button.center.x
                underlineView.backgroundColor = UIColor ( red: 0.3239, green: 0.5661, blue: 0.8103, alpha: 1.0 )
                underlineView.tag = 800 + i
                self.headerView.addSubview(underlineView)
            }
        }
    }
    
    
    
    // 数据请求完毕刷新的方法
    func _requextSuccessNext()
    {
        let url = URL(string: self.headImageUrlString)
        self.headerImageView .sd_setImage(with: url)
    }
    

    //MARK: - 网络请求数据
    func _requestDataList()
    {
        // 请求头视图数据
        self.requestHead()
        
        // 请求cell的数据
        self.requestCell()
    }
    
    // 请求头视图数据
    func requestHead()
    {
        // 请求最上面的图片
        let urlString1 = HttpUrl + "/shop/banner/image/get"
        let requestHead1:[String:String] = ["version":"2.0","terminal":"ios"]
        let request1 = HTTPRequest()
        request1.POSTRequest(urlString1, httpHeader: requestHead1, parameters: nil, resultBlock: { (result) -> Void in
//            print("请求成功")
//            print(result)
            // 获取数据
            var data:Array<AnyObject> = result["data"] as! Array
            let dic:[String:AnyObject] = data[0] as! Dictionary
            self.headImageUrlString = dic["url"] as! String
            // 刷新视图
            self._requextSuccessNext()
            
            }) { () -> Void in
//                print("请求失败")
        }
        
        // 请求中间物品信息的数据
        let urlString2 = HttpUrl + "/shop/goods/page/get"
        let requestHead2:[String:String] = ["version":"2.0","terminal":"ios"]
        let request2 = HTTPRequest()
        let dic:[String:String] = ["recommend":String(1)]
        request2.POSTRequest(urlString2, httpHeader: requestHead2, parameters: dic, resultBlock: { (result) -> Void in
//            print("请求成功")
//            print(result)
            
            let data:[String:AnyObject] = result["data"] as! Dictionary
            let list:Array<AnyObject> = data["list"] as! Array
            for dic:AnyObject in list
            {
                let itemShow_Mall = ItemShow_Mall(contentDic:dic as! [AnyHashable: Any])
                self.itemShowArray.append(itemShow_Mall!)
            }
//            print(self.itemShowArray.count)
            // 刷新表格
            self.collectionView .reloadData()
            }) { () -> Void in
//                print("请求失败")
        }
        
        
    }
    
    
    // 请求cell里面的数据
    func requestCell()
    {
        // 请求默认列表的数据
        self.requestCell_default()
    }
    
    // 请求默认列表的数据
    func requestCell_default()
    {
        let urlString = HttpUrl + "/shop/goods/page/get"
        let requestHead:[String:String] = ["version":"2.0","terminal":"ios"]
        let parmDic:[String:String] = ["pageSize":String(20),"orderByType":"default","page":String(self.default_Page)]
        let request = HTTPRequest()
        request.POSTRequest(urlString, httpHeader: requestHead, parameters: parmDic, resultBlock: { (result) -> Void in
//            print("请求成功")
//            print(result)

            let data:[String:AnyObject] = result["data"] as! Dictionary
            let list:Array<AnyObject> = data["list"] as! Array
            for dic:AnyObject in list
            {
                let itemShow_Mall = ItemShow_Mall(contentDic:dic as! [AnyHashable: Any])
                self.defaultArray.append(itemShow_Mall!)
            }
            // 刷新表格
            self.overallTableView.reloadData()

            
            }) { () -> Void in
                print("请求失败")
        }
    }
    
    
    //MARK: - 响应事件
    func buttonAction(_ sender:UIButton)
    {
        for i in 0  ..< 3 
        {
            let button = self.headerView.viewWithTag(140+i) as! UIButton
            button.setTitleColor(UIColor ( red: 0.4337, green: 0.4337, blue: 0.4337, alpha: 1.0 ), for: UIControlState())
        }
        sender.setTitleColor(UIColor.black, for: UIControlState())
        
        UIView.animate(withDuration: 0.2, animations: { () -> Void in
            let underlineView = self.headerView.viewWithTag(800)
            underlineView?.center.x = sender.center.x
            })
    }
    

    //MARK: - collectionView的代理和数据源方法
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.itemShowArray.count ;
    }
    
    func  collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Ccell", for: indexPath) as! ItemsShowCCell
        cell.ISModel_Mall = self.itemShowArray[(indexPath as NSIndexPath).row] as! ItemShow_Mall
        // 复用
//        cell.setNeedsLayout()
        cell.layoutIfNeeded()
        return cell 
    }
    
    
    
    //MARK: - tableView的代理方法
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.defaultArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Tcell") as! ItemShowTCell
        cell.selectionStyle = .none
        cell.itemShow_Mall = self.defaultArray[(indexPath as NSIndexPath).row] as! ItemShow_Mall
        cell .setNeedsLayout()
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
}
